import { message } from "ant-design-vue";
import { customizeImportApi } from "@/api/waybillManagement/businessWaybill";

export default function OperationHook(state: Base.GeneraDataType) {
  const { passData, formState, formRef, emit, dataList, saveOrExportStatus, type } = state;

  const onSubmit = () => {
    formRef.value.validate().then(() => {
      let params: any;

      if (passData.value.selectRows.length) {
        params = {
          ...formState,
          buttonType: saveOrExportStatus.value === "1" ? 1 : 2,
          selectStatus: type.value,
          idList: passData.value.selectRows.map((t: any) => t.id)
        };
      } else {
        params = {
          ...formState,
          ...passData.value.searchForm,
          buttonType: saveOrExportStatus.value === "1" ? 1 : 2,
          selectStatus: type.value
        };
      }

      const result: any = [];
      const nameArr: any = [];
      dataList.value.map((t: any) => {
        t.feilds.map((q: any) => {
          if (t.checkValue.includes(q.code)) {
            result.push(q.code);
            nameArr.push(q.name);
          }
        });
      });
      params.fieldList = result;
      params.nameList = nameArr;
      if (!params.fieldList.length) return message.error("请选择导出内容");
      customizeImportApi(params).then((res: any) => {
        const { code } = res;
        if (code === 200) {
          message.success("创建任务成功，请前往导出中心下载！");
          emit("submit");
          resetForm();
        }
      });
    });
  };
  const resetForm = () => {
    formRef.value.resetFields();
    formState.exportName = undefined;
    saveOrExportStatus.value = "1";
    emit("update:visible", false);
  };

  const saveHandle = () => {
    formRef.value.validate().then(() => {
      let result: any = [];
      dataList.value.map((t: any) => {
        result = result.concat(...t.checkValue);
      });
      if (!result.length) return message.error("请选择导出内容");
      saveOrExportStatus.value = "2";
    });
  };
  const changeName = (e: any, option: any) => {
    formState.type = option.label;
  };
  return {
    resetForm,
    onSubmit,
    saveHandle,
    changeName
  };
}
